package org.orz.story.pms.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.orz.cloud.auth.UserUtil;
import org.orz.cloud.auth.domain.UserInfo;
import org.orz.cloud.common.enums.AliveFlagEnum;
import org.orz.story.pms.biz.model.req.*;
import org.orz.story.pms.biz.model.resp.ListApiInfoWithPermitStatusResp;
import org.orz.story.pms.biz.persistence.entities.PmsApi;
import org.orz.story.pms.biz.persistence.entities.PmsPermissionApi;
import org.orz.story.pms.biz.persistence.entities.PmsRoleApi;
import org.orz.story.pms.biz.persistence.mappers.PmsApiMapper;
import org.orz.story.pms.biz.persistence.mappers.PmsPermissionApiMapper;
import org.orz.story.pms.biz.persistence.mappers.PmsRoleApiMapper;
import org.orz.story.pms.biz.service.PmsApiService;
import org.orz.story.pms.common.exception.PmsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PmsApiServiceImpl implements PmsApiService {
    @Autowired
    private PmsApiMapper pmsApiMapper;
    @Autowired
    private PmsPermissionApiMapper pmsPermissionApiMapper;
    @Autowired
    private PmsRoleApiMapper pmsRoleApiMapper;


    @Override
    public Page<PmsApi> listApiInfo(ListApiInfoReq req) {
        LambdaQueryWrapper<PmsApi> wrapper = new LambdaQueryWrapper<PmsApi>()
                .eq(PmsApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey());
        wrapper.orderByDesc(PmsApi::getId);
        PageHelper.startPage(req.getPageInfo().getPageNum(), req.getPageInfo().getPageSize());
        return (Page<PmsApi>) pmsApiMapper.selectList(wrapper);
    }

    @Override
    public Page<ListApiInfoWithPermitStatusResp> listApiInfoWithPermitStatus(ListApiInfoWithPermitStatusReq req) {
        PageHelper.startPage(req.getPageInfo());
        Page<PmsApi> apis = (Page<PmsApi>) pmsApiMapper.selectList(new LambdaQueryWrapper<PmsApi>()
                .eq(PmsApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey())
                .orderByDesc(PmsApi::getId));
        if(CollUtil.isEmpty(apis)){
            return new Page<>();
        }
        // 查询当前权限是否已经配置查询出的接口
        List<PmsPermissionApi> permissionApis = pmsPermissionApiMapper.selectList(new LambdaQueryWrapper<PmsPermissionApi>()
                .eq(PmsPermissionApi::getPermissionId, req.getPermissionId())
                .eq(PmsPermissionApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));
        Set<Long> selectedApiIds = permissionApis.stream().map(PmsPermissionApi::getApiId).collect(Collectors.toSet());


        List<ListApiInfoWithPermitStatusResp> resultList = apis.stream().map(item -> {
            ListApiInfoWithPermitStatusResp resultData = new ListApiInfoWithPermitStatusResp();
            resultData.setId(item.getId());
            resultData.setApiName(item.getApiName());
            resultData.setApiUrl(item.getApiUrl());
            resultData.setCreateDate(item.getCreateDate());
            resultData.setUpdateDate(item.getUpdateDate());
            resultData.setCheckedFlag(selectedApiIds.contains(item.getId()));
            return resultData;
        }).collect(Collectors.toList());
        Page<ListApiInfoWithPermitStatusResp> result = new Page<>();
        result.setPageNum(req.getPageInfo().getPageNum());
        result.setPageSize(req.getPageInfo().getPageSize());
        result.setPages(apis.getPages());
        result.setTotal(apis.getTotal());
        result.addAll(resultList);
        return result;
    }

    @Override
    public List<PmsApi> listApiByPermissionId(ListApiByPermissionIdReq req) {
        PageHelper.startPage(req.getPageInfo());
        return pmsApiMapper.listApiByPermissionId(req.getPermissionId());
    }

    @Override
    public void addApi(AddApiReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        // 1.查询接口是否重复
        List<PmsApi> pmsApis = pmsApiMapper.selectList(new LambdaQueryWrapper<PmsApi>()
                .eq(PmsApi::getApiUrl, req.getApiUrl())
                .eq(PmsApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));
        if(CollUtil.isNotEmpty(pmsApis)){
            throw new PmsException(PmsException.Type.PMS_0003);
        }

        // 2.保存接口
        PmsApi insertParam = new PmsApi();
        insertParam.setApiName(req.getApiName());
        insertParam.setApiUrl(req.getApiUrl());
        insertParam.setCreateUser(userInfo.getAccountId());
        insertParam.setCreateDate(new Date());
        pmsApiMapper.insert(insertParam);
    }

    @Override
    public void updateApi(UpdateApiReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        PmsApi pmsApi = new PmsApi();
        pmsApi.setId(req.getId());
        pmsApi.setApiName(req.getApiName());
        pmsApi.setApiUrl(req.getApiUrl());
        pmsApi.setUpdateUser(userInfo.getAccountId());
        pmsApi.setUpdateDate(new Date());
        pmsApiMapper.updateById(pmsApi);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteApi(DeleteApiReq req) {
        UserInfo userInfo = UserUtil.getUserInfoWithExistCheck();
        // 删除的同时要更新角色接口表、权限接口表的关系
        // 1.删除接口
        PmsApi deleteParam = new PmsApi();
        deleteParam.setId(req.getId());
        deleteParam.setAliveFlag(AliveFlagEnum.DELETED.getKey());
        deleteParam.setUpdateUser(userInfo.getAccountId());
        deleteParam.setUpdateDate(new Date());
        pmsApiMapper.updateById(deleteParam);

        // 2.删除接口相关的关联关系
        PmsPermissionApi permissionApi = new PmsPermissionApi();
        permissionApi.setAliveFlag(AliveFlagEnum.DELETED.getKey());
        permissionApi.setUpdateUser(userInfo.getAccountId());
        permissionApi.setUpdateDate(new Date());
        pmsPermissionApiMapper.update(permissionApi, new LambdaQueryWrapper<PmsPermissionApi>()
                    .eq(PmsPermissionApi::getApiId, req.getId())
                    .eq(PmsPermissionApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));

        PmsRoleApi pmsRoleApi = new PmsRoleApi();
        pmsRoleApi.setAliveFlag(AliveFlagEnum.DELETED.getKey());
        pmsRoleApi.setUpdateUser(userInfo.getAccountId());
        pmsRoleApi.setUpdateDate(new Date());
        pmsRoleApiMapper.update(pmsRoleApi, new LambdaQueryWrapper<PmsRoleApi>()
                .eq(PmsRoleApi::getApiId, req.getId())
                .eq(PmsRoleApi::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));
    }
}
